<template>
  <div class="top-toolbar">
    <el-input
        :model-value="canvasData.name"
        @input="handleNameChange"
        placeholder="点击编辑名称"
        maxlength="50"
        suffix-icon="el-icon-edit"
        :show-word-limit="true"/>
<!--    <el-button @click="test">1测试</el-button>-->
<!--    <el-button @click="test2">2测试</el-button>-->

    <template v-if="from === 'merchant'">
      <el-button @click="update" v-if="$route.query.id">更新草稿</el-button>
      <el-button @click="save" v-else>保存草稿</el-button>
      <el-button type="primary" @click="publish">发布</el-button>
    </template>

    <template v-if="from === 'merchantTemplate'">
      <el-button @click="saveMerchantModel">从模板保存草稿</el-button>
      <el-button type="primary" @click="publishMerchantModel">从模板发布</el-button>
    </template>

    <template v-if="from === 'sass'">
      <el-button type="primary" @click="updateModel" v-if="$route.query.modelId">更新流程模板</el-button>
      <el-button type="primary" @click="createModel" v-else>发布流程模板</el-button>
    </template>
  </div>
</template>

<script>
import {CanvasCreateModel} from "../dataModel/canvasCreate";

import CanvasApi from "@/api/canvasApi";
import CustomerApi from "@/api/customerApi";
import useFrom from "../compositions/useFrom";
import {useIFrameOrigin} from "../compositions/useSrc";
import {DataUri} from "@antv/x6";
import {upload} from "../../../utils/minio-upload";

export default {
  props: {
    graph: Object,
    canvasData: Object,
  },

  emits: [
      'submitted',
  ],

  data(){
    return {
      // from: 'merchant'
    }
  },

  computed: {
  },

  setup(props) {
    // const from = useFrom({canvasData: props.canvasData})
    const origin = useIFrameOrigin()

    const from = computed(() => {
      // console.log('from computed', useFrom({canvasData: props.canvasData}))
      // console.log('from canvasData', props.canvasData)
      return useFrom({canvasData: props.canvasData})
    })

    return {
      from,
      origin
    }
  },

  updated() {
    // console.log('canvasData updated', this.canvasData)
  },

  methods: {
    test() {
      console.log('test', this.canvasData)
      const nodes = this.graph.getNodes()
      const placeholderNodes = nodes.filter(node => node.shape === 'placeholder')
      const dataList = placeholderNodes.map(item => item.getData())
      console.log('placeholderNodes', dataList)
    },

    test2(){
      console.log('test2')
    },

    handleNameChange(val) {
      this.canvasData.name = val.trim();
      clearTimeout(this.nameChangeTimer);
      this.nameChangeTimer = setTimeout(() => {
        const graphData = this.graph.toJSON();
        const startCellModel =
            graphData.cells &&
            graphData.cells.find((cell) => cell.shape === "start");
        if (startCellModel) {
          const startCell = this.graph.getCellById(startCellModel.id);
          startCell.setData({
            dialogData: {
              name: this.canvasData.name,
            },
          });
          startCell.trigger("change:data", {current: startCell.getData()});
        }
      }, 1000);
    },

    preCheckData() {
      function setCheckResult(result, message) {
        return {
          result: result,
          message: message,
        }
      }

      const edges = this.graph.getEdges();
      const nodes = this.graph.getNodes();

      if (!nodes.length) {
        return setCheckResult(false, "请先添加节点");
      }

      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        const nodeData = nodes[i].getData()
        const nodeName = nodeData?.dialogData?.name ?? "有节点";
        const targetEdge = edges.find(
            (edge) => node.id === edge.getTarget().cell
        );
        if (!targetEdge && node.shape !== "start") {
          return setCheckResult(false, `${nodeName}缺少连接线，请检查`);
        }
        //
        //
        // if (!nodeData.validateResult || !nodeData.validateResult.result) {
        //   return setCheckResult(false, `${nodeName}的节点表单不完整，请双击节点完成填写。${nodeData?.validateResult?.message ?? ''}`)
        // }
      }

      if (nodes.find(node => node.shape === 'placeholder')) {
        return setCheckResult(false, '还有占位节点未被替换，请检查')
      }

      if (!this.canvasData.name) {
        return setCheckResult(false, '流程名称还未填写')
      }

      if (this.from === 'merchantTemplate') {
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i]
          const nodeData = node.getData()
          const name = nodeData.dialogData?.name ?? "未命名节点";
          const shape = node.shape
          const {merchantTemplateFormValidateResult} = nodeData

          if (!merchantTemplateFormValidateResult || !merchantTemplateFormValidateResult.result) {
            if (shape !== 'end') {
              return setCheckResult(false, `节点：${name}的表单不完整，请双击节点填写表单`)
            }
          }
        }
      }

      return setCheckResult(true, '');
    },

    formatServerData() {
      const {canvas, nodes, relations, events} = new CanvasCreateModel({
        graph: this.graph,
      }).transferDataToServer({
        canvasData: this.canvasData,
        graphData: this.graph.model.toJSON(),
        eventsData: this.eventsData,
      });

      return {
        canvas,
        nodes,
        relations,
        events,
      };
    },

    async update() {
      const preCheckResult = this.preCheckData();
      if (!preCheckResult.result) {
        ElMessage.error(preCheckResult.message);
        return;
      }

      const data = this.formatServerData();
      const rs = await CanvasApi.updateCanvas(data);

      if (rs.code !== 200) {
        return;
      }

      this.$message.success("更新成功");
      await this.$router.replace(`workTable?id=${rs.payload.id}`);
      this.canvasData.id = rs.payload.id;

      this.$emit('submitted')

      return Promise.resolve(rs);
    },

    async save({hideMessage = false}) {
      const preCheckResult = this.preCheckData();
      if (!preCheckResult.result) {
        ElMessage.error(preCheckResult.message);
        return;
      }

      const data = this.formatServerData();
      const rs = await CanvasApi.createCanvas(data);

      if (rs.code !== 200) {
        return Promise.reject(rs.error);
      }

      !hideMessage && this.$message.success("保存成功");
      await this.$router.replace(`workTable?id=${rs.payload.id}`);
      this.canvasData.id = rs.payload.id;

      this.$emit('submitted')
      return Promise.resolve(rs);
    },

    publish() {
      const firstStep = this.$route.query.id
          ? this.update()
          : this.save({hideMessage: true});
      return firstStep
          .then(async (saveRs) => {
            if (!saveRs) {
              return Promise.reject("保存草稿失败");
            }

            let publishRs = await CustomerApi.publishCanvas({
              id: saveRs.payload.id,
              name: saveRs.payload.name
            });

            if (publishRs.code !== 200) {
              return Promise.reject("发布失败");
            }

            this.$message.success("发布成功");
            setTimeout(() => {
              this.$router.back();
            }, 1000);
          })
          .catch((e) => {
            // this.$message.error(e)
          });
    },

    uploadGraphImg() {
      return new Promise(resolve => {
        this.graph.toPNG(async (dataUri) => {
          const blob = DataUri.dataUriToBlob(dataUri)
          const file = new File([blob], 'flow_template_' + this.canvasData.name + '.png', {type: 'image/png'});

          const {url} = await upload(file, 'sass/worktable')

          resolve(url)
        })
      })
    },

    async createModel() {
      const preCheckResult = this.preCheckData();
      if (!preCheckResult.result) {
        ElMessage.error(preCheckResult.message);
        return;
      }

      const data = this.formatServerData();
      data.canvas.previewImgUrl = await this.uploadGraphImg()
      const createModelMessage = {
        method: 'createModel',
        args: data
      }
      parent.postMessage(createModelMessage, this.origin)
    },

    async updateModel() {
      const preCheckResult = this.preCheckData();
      if (!preCheckResult.result) {
        ElMessage.error(preCheckResult.message);
        return;
      }

      const data = this.formatServerData();
      data.canvas.previewImgUrl = await this.uploadGraphImg()
      const updateModelMessage = {
        method: 'updateModel',
        args: data
      }
      parent.postMessage(updateModelMessage, this.origin)
    },

    async saveMerchantModel({hideMessage=false, stopReload=false}) {
      const preCheckResult = this.preCheckData();
      if (!preCheckResult.result) {
        ElMessage.error(preCheckResult.message);
        return;
      }

      const data = this.formatServerData();
      const rs = await CanvasApi.createCanvas(data);

      if (rs.code === 200) {
        !hideMessage && this.$message.success("保存成功");
        await this.$router.replace(`workTable?id=${rs.payload.id}`);
        !stopReload && location.reload()
      }

      return rs
    },

    async publishMerchantModel() {
      const saveRs = await this.saveMerchantModel({hideMessage: true, stopReload: true})

      if (saveRs && saveRs.code !== 200) {
        ElMessage.error('保存草稿失败')
        return
      }

      const publishRs = await CustomerApi.publishCanvas({
        id: saveRs.payload.id,
        name: saveRs.payload
      });

      if (publishRs.code === 200) {
        ElMessage.success("发布成功");
        this.$router.back()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.top-toolbar {
  padding: 0 25px;
  height: 80px;
  display: flex;
  align-items: center;
  box-shadow: 0 5px 6px -1px rgba(0, 0, 0, 0.06);

  :deep(.el-input) {
    margin-right: 16px;

    .el-input__inner {
      border: unset;
    }
  }
}
</style>
